'use client';

import { SVGProps, useEffect, useMemo, useRef, useState } from 'react';
import './CategoriesMenu.scss';
import { useActions, useGlobalState } from '@/hooks';
import Link from 'next/link';
import { NextPage } from 'next';
import FontIcon from '../FontIcon';
import CategoriesSub from './CategoriesSub';

const rootId = Number(process.env.NEXT_PUBLIC_ROOT_CATEGORY_ID);

const getCategoryLink = (cat: Obj, categories: any[] | null) => {
  let currCat = { ...cat };
  if (!currCat.url_key) return '';
  const pathArray = [currCat.url_key];
  while (currCat?.parent_id && currCat?.parent_id != rootId) {
    currCat = categories?.find(c => c.category_id == currCat.parent_id);
    if (currCat) pathArray.push(currCat.url_key);
  }
  return '/categories/' + pathArray.reverse().join('/');
};

const CategoriesMenu: NextPage = () => {
  const categories = useGlobalState('product', 'categoryList');

  const categoriesLv1 = useMemo(() => {
    const lv1_list = categories.filter((d: any) => d.parent_id == rootId);
    return lv1_list;
  }, [categories]);

  const [hoverCategory1, seHoverCategory1] = useState<any>(null);
  const [viewMenu, setViewMenu] = useState<any>(false);
  const [viewMenuSub, setViewMenuSub] = useState<any>(false);

  const handleItemOver = (e: any) => {
    if (e.currentTarget?.dataset?.category_id) {
      const cat = e.currentTarget?.dataset;
      seHoverCategory1({ ...cat });
      setViewMenuSub(true);
    }
  };
  const handleMouseButtonEnter = (e: any) => {
    e.stopPropagation();
    setViewMenu(true);
    setViewMenuSub(false);
    // setOverCategoryId1(null)
    seHoverCategory1(null);
  };
  const handleMouseButtonLeave = () => {
    setViewMenu(false);
  };
  const handleMouseMenuEnter = (e: any) => {
    e.stopPropagation();
    setViewMenu(true);
  };
  const handleMouseMenuLeave = () => {
    setViewMenu(false);
    setViewMenuSub(false);
  };
  const handleMouseSubEnter = (e: any) => {
    e.stopPropagation();
    setViewMenuSub(true);
  };
  const handleMouseSubLeave = () => {
    setViewMenuSub(false);
  };

  function adjustGridHeight() {
    const gridItems = document.querySelectorAll('.category-block');
    const itemHeights = Array.from(gridItems).map(
      (item: any) => item.offsetHeight
    );
    const maxHeight = Math.max(...itemHeights);
    document.documentElement.style.setProperty(
      '--grid-auto-rows',
      `${maxHeight}px`
    );
  }
  useEffect(() => {
    adjustGridHeight();
  }, [hoverCategory1]);

  useEffect(() => {
    const element = document.querySelector('.main-menu-category-level-1-list');
    if (element && categoriesLv1?.length) {
      const style = window.getComputedStyle(element);
      const lv1_height = element?.clientHeight + parseInt(style.marginTop);
      lv1_height &&
        document
          .querySelector('.main-menu-category-level-1')
          ?.setAttribute('style', 'height: ' + lv1_height + 'px;');
      // console.log('🟢🟢🟢Categories Menu init ', lv1_height);
    }
  }, [categoriesLv1]);

  return (
    <div className="main-menu-category-wrapper">
      <button
        className="main-menu-category-button"
        onMouseEnter={handleMouseButtonEnter}
        onMouseLeave={handleMouseButtonLeave}
      >
        Categories
        <FontIcon
          className={
            'main-menu-category-button-arrow ' +
            (viewMenu || viewMenuSub ? 'arrow-up' : 'arrow-down')
          }
          style={{ width: '18px', height: '18px' }}
          name="expand-line"
        />
      </button>
      <div className="main-menu-category-dropdown">
        <div
          className={
            'main-menu-category-level-1 ' +
            (viewMenu || viewMenuSub ? 'show-list' : 'hide-list')
          }
          onMouseEnter={handleMouseMenuEnter}
          onMouseLeave={handleMouseMenuLeave}
        >
          <div className="main-menu-category-level-1-list">
            {categoriesLv1.map((ca: any, index: number) => (
              <li
                key={index}
                onMouseOver={handleItemOver}
                data-category_id={ca.category_id}
                data-parent_id={ca.parent_id}
                data-title={ca.title}
                data-url_key={ca.url_key}
                className={
                  'category-item ' +
                  (hoverCategory1?.category_id == ca.category_id
                    ? 'active'
                    : '')
                }
              >
                <Link href={getCategoryLink(ca, categories)}>
                  {ca.title}
                  {hoverCategory1?.category_id == ca.category_id && (
                    <FontIcon
                      name="forward-line"
                      style={{ width: '18px', height: '18px' }}
                    />
                  )}
                </Link>
              </li>
            ))}
          </div>
        </div>
        <div
          className={
            'main-menu-category-level-2 ' +
            (viewMenuSub ? 'show-list' : 'hide-list')
          }
          onMouseEnter={handleMouseSubEnter}
          onMouseLeave={handleMouseSubLeave}
        >
          <CategoriesSub
            hoverCategory1={hoverCategory1}
            categories={categories}
          />
        </div>
      </div>
    </div>
  );
};

export default CategoriesMenu;
